
import { Component, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { SignalRService } from '../../shared/services/signalR.service';
import { Subscription } from 'rxjs/Subscription';
import { LrtmService, LongRunningTaskInstanceStatusEnum } from './lrtm.service';
import { RefreshTokenService } from '../../shared/services/refreshToken.service';
import * as _ from 'lodash';

@Component({
    moduleId: module.id,
    templateUrl: 'lrtm.component.html',
    selector: 'lrtm',
    changeDetection: ChangeDetectionStrategy.OnPush,
    styleUrls: ['./lrtm.component.scss']
})
export class LrtmComponent {
    private _hubName = 'LongRunningTaskHub';
    private _service = 'lrtmserv';
    private _sub: Subscription;
    private _refreshSub: Subscription;
    private _action: (value: any) => void = data => {
        if (!_.isEqual(this.lrtmService.tasks, data)) {
            this.lrtmService.tasks = data;
            //we must force change detect on child elements(service tasks)
            this.cdRef.detectChanges();
        }
    }
    private _error: (error: any) => void = error => {
        this.lrtmService.tasks = undefined;
        throw error;
    }
    public expanded = true;

    constructor(private signalRService: SignalRService, 
        public lrtmService: LrtmService, 
        public refreshTokeService: RefreshTokenService,
        private cdRef: ChangeDetectorRef) { }

    ngOnInit() {
        //create connection on framework init (on login). Disconnected on logout and connection reset to undefined
        this._sub = this.signalRService.connect(this._hubName, this._service, _ => { this.lrtmService.setMaxTasksPerUser() }).subscribe(this._action, this._error);

        //on token refresh, reconnect to signalr using new token
        this._refreshSub = this.refreshTokeService.storage.subscribe(data => {
            console.log('SignalR reconnecting...');
            this.signalRService.disconnect();
            this.signalRService.connect(this._hubName, this._service, _ => { this.lrtmService.setMaxTasksPerUser() }).subscribe(this._action, this._error);            
        });
    }

    ngOnDestroy() {
        if (this._refreshSub) this._refreshSub.unsubscribe();
        if (this._sub) this._sub.unsubscribe();
    }

    get numCompletedTasks(): number {
        return this.lrtmService.tasks.filter(task => {
            // complete
            return (task.taskStatus.progress === 100) || task.taskInstanceStatus !== LongRunningTaskInstanceStatusEnum.Running;
        }).length;
    }

    get percentComplete(): number {
        return this.numCompletedTasks / this.lrtmService.tasks.length * 100;
    }
}
